<template>
  <section class="app-inner">
    <el-card class="header-card">
      <el-form :inline="true" :model="form" size="small">
        <el-form-item label="任务名称">
          <el-input v-model="form.planName" clearable placeholder="请输入任务名称" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="巡检执行人">
          <el-input v-model="form.userName" clearable placeholder="请输入巡检执行人" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
            v-model="form.startTime"
            type="date"
            placeholder="请输入开始日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptionsStart"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
            v-model="form.endTime"
            type="date"
            placeholder="请输入结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptionsEnd"
          ></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="margin-left: 10px;">查 询</el-button>
        </el-form-item>
        <el-form-item class="createBtn">
          <el-button type="primary" @click="createTask" style="margin-left: 10px;">创建计划任务</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="table-card">
      <el-table border :data="tableData" style="width: 100%">
        <el-table-column prop="planCode" label="任务编号" width="200"></el-table-column>
        <el-table-column prop="planType" label="任务类型">
          <template slot-scope="scope">
            {{ getLabel(scope.row.planType) }}
          </template>
        </el-table-column>
        <el-table-column prop="planName" label="任务名称"></el-table-column>
        <el-table-column prop="taskOperatorUserName" label="巡检执行人" width="120"></el-table-column>
        <el-table-column prop="planStartTime" label="计划开启巡检时间" width="160"></el-table-column>
        <el-table-column prop="isValid" label="巡检状态" :formatter="formatter" width="120"></el-table-column>
        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button v-if="scope.row.isValid === 1" @click="handleSetting(scope.row)" type="text" size="small"
              >设为无效</el-button
            >
            <el-button v-else @click="handleSetting(scope.row)" type="text" size="small">设为有效</el-button>
            <el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        layout="total, prev, pager, next"
        @current-change="pageHandleChange"
        :current-page="currentPage"
        :total="totalPageNum"
        :page-size="pageSize"
      ></el-pagination>
    </el-card>
    <!-- 选择巡检人按钮 弹框 -->
    <el-dialog
      :title="eventControl"
      :visible.sync="dialogChoseVisible"
      center
      :before-close="closedChose"
      class="handle"
    >
      <el-form ref="choseFormRef" :model="editForm" :rules="rules">
        <el-transfer
          v-model="InspectorValue"
          :data="userArray"
          :titles="['可选择巡检人', '选中执行人']"
          :button-texts="['撤销', '选中']"
          @left-check-change="checkChange"
        ></el-transfer>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedChose">取消</el-button>
        <el-button type="primary" @click="handleChoseEvent">确定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { getPlan, deletePlan, updatePlanValid } from './js/patrol'
import { taskStatus, week, planTypeList } from './js/constants'
export default {
  data () {
    return {
      eventControl: '',
      dialogHandleVisible: false,
      dialogChoseVisible: false,
      currentPage: 1,
      totalPageNum: 0,
      pageSize: 10,
      weekList: week,
      form: {
        planName: '',
        userName: '',
        startTime: '',
        endTime: ''
      },
      searchData: {
        planName: '',
        userName: '',
        planStartTimeFrom: '',
        planStartTimeTo: ''
      },
      editForm: {
        planCode: '',
        planName: '',
        userId: '',
        userName: '',
        startDate: '',
        startTime: '',
        endTime: '',
        valid: true,
        period: '',
        uploadImage: ''
      },
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime()
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          if (this.form.startTime) {
            return time.getTime() < new Date(this.form.startTime).getTime() - 86400000
          }
        }
      },
      rules: {
        staff: [{ required: true, message: '维修人不能为空', trigger: 'blur' }]
      },
      maintainer: [],
      tableData: [],
      userArray: [],
      InspectorValue: [],
      leftChecked: []
    }
  },
  components: {},
  mounted () {
    this.getPlanList(this.searchData)
  },
  methods: {
    formatter (row, column, cellValue) {
      return this.$base.constFormatter(taskStatus, cellValue)
    },
    onSubmit () {
      this.currentPage = 1
      this.searchData = {
        planName: this.form.planName,
        userName: this.form.userName,
        planStartTimeFrom: this.form.startTime,
        planStartTimeTo: this.form.endTime
      }
      this.getPlanList(this.searchData)
    },
    async getPlanList (data) {
      let params = {
        ...data,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      }
      // if (data) {
      //   params = {
      //     ...data,
      //     pageNum: this.currentPage,
      //     pageSize: 10
      //   }
      // } else {
      //   params = {
      //     pageNum: this.currentPage,
      //     pageSize: 10
      //   }
      // }
      let res = await getPlan(params)
      this.totalPageNum = res.data.total
      res = res.data.list
      res.forEach(item => {
        if (item.isValid) {
          item.valid = 1
          item.btnFlag = 1
        } else {
          item.valid = 0
          item.btnFlag = 0
        }
        if (item.validStartTime && item.validEndTime) {
          item.validStartTime = item.validStartTime.substring(0, item.validStartTime.length - 3)
          item.validEndTime = item.validEndTime.substring(0, item.validEndTime.length - 3)
        }
      })
      this.tableData = res
    },
    createTask () {
      // this.$router.push({ name: 'patrolCreatePlan' })
      this.$router.push({ path: 'CreatePlan' })
    },
    // 设为无效
    handleSetting (row) {
      // row.btnFlag = !row.btnFlag
      let str = ''
      if (row.isValid === 0) {
        str = '为有效'
      } else {
        str = '为无效'
      }
      this.$confirm('您确定设置该任务' + str + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.updatePlanValidFun(row)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消设置'
          })
        })
    },
    async updatePlanValidFun (row) {
      let params = {
        planCode: row.planCode
      }
      let res = await updatePlanValid(params)
      if (res.code === 0) {
        this.$message.success('设置成功！')
      }
      await this.getPlanList(this.searchData)
    },
    changeValid () {
      this.editForm.valid = !this.editForm.valid
    },
    handleEdit (row) {
      // this.$router.push({ name: 'patrolSetting', params: row })
      this.$router.push({ path: 'Setting', query: { row: JSON.stringify(row) } })
    },
    // handleEditEvent (editFormRef) {
    //   this.$refs[editFormRef].validate(async (valid) => {
    //     if (valid) {
    //       let params = {
    //         'needUploadImage': this.editForm.uploadImage,
    //         'planCode': this.editForm.planCode,
    //         'planName': this.editForm.planName,
    //         'planPeriodByFront': this.editForm.period,
    //         'planStartTime': this.editForm.startDate,
    //         'taskOperatorUserNo': this.editForm.userId,
    //         'valid': this.editForm.valid,
    //         'validEndTime': `${this.editForm.endTime}:00`,
    //         'validStartTime': `${this.editForm.startTime}:00`
    //       }
    //       let res = await updatePlan(params)
    //       if (res.code === 0) {
    //         this.$message.success('设置成功！')
    //       }
    //       await this.getPlanList()
    //       this.dialogHandleVisible = false
    //       this.$refs.editFormRef.resetFields()
    //     }
    //   })
    // },
    // closedEdit () {
    //   this.dialogHandleVisible = false
    //   this.$refs.editFormRef.resetFields()
    // },
    handleDelete (row) {
      let deleteArr = []
      deleteArr.push(row.planCode)
      this.$confirm('是否确认删除该任务?', '审核', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let params = {
          planCodeList: deleteArr
        }
        let res = await deletePlan(params)
        if (res.code === 0) {
          this.$message.success('删除成功！')
          if (this.tableData.length === 1 && this.currentPage > 1) {
            this.currentPage--
          }
        }
        await this.getPlanList(this.searchData)
      })
    },
    checkChange () {},
    // 巡检人选择确定按钮
    handleChoseEvent () {
      let str = ''
      let checkedUserId = ''
      let InsArray = this.InspectorValue
      this.userArray.forEach(item => {
        if (InsArray.indexOf(item.key) !== -1) {
          checkedUserId = item.key
          str = item.label
        }
      })
      this.editForm.userName = str
      this.editForm.userId = checkedUserId
      this.dialogChoseVisible = false
    },
    closedChose () {
      this.dialogChoseVisible = false
    },
    pageHandleChange (page) {
      this.currentPage = page
      this.getPlanList(this.searchData)
    },
    getLabel (val) {
      return this.$base.constFormatter(planTypeList, val)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-inner {
  height: 100%;
  .header-card {
    margin-bottom: 10px;
    .el-form {
      .el-form-item {
        .el-input {
          width: 160px;
        }
      }
      // .createBtn {
      //   float: right;
      // }
    }
  }
  .el-pagination {
    text-align: center;
    display: block;
    margin: 10px auto;
  }
  .img-over {
    margin-right: 5px;
    width: 60px;
    height: 45px;
    cursor: pointer;
  }
  .handle {
    .el-form {
      .el-form-item {
        .set-input {
          width: 72%;
        }
        .sel-time {
          width: 36%;
        }
        .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
